﻿using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Read.Apilication.Common.Menu;
using B.S.BasicData.Read.DTOS;
using MediatR;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace B.S.BasicData.Read.Apilication.Handler.Menu
{
    public class MenuShowCommandHandle : IRequestHandler<MenuShowCommand, ApiPaimg<MenuNameDto>>
    {
        private readonly IBaseRepository<MenuModel> MenuDal;

        public MenuShowCommandHandle(IBaseRepository<MenuModel> menuDal)
        {
            MenuDal = menuDal;
        }

        public Task<ApiPaimg<MenuNameDto>> Handle(MenuShowCommand request, CancellationToken cancellationToken)
        {
            ApiPaimg<MenuNameDto> result = new ApiPaimg<MenuNameDto>();

            var list = MenuDal.GetAll().Where(x => x.IsDeleted == false);

            var linq = from a in list
                       join b in list.DefaultIfEmpty()//左连接 处理顶级菜单
                       on a.ParentId equals b.MenuId
                       into OrderId
                       from b in OrderId.DefaultIfEmpty()   //确保左连接语义 DefaultIfEmpty当集合为空的时候 返回一个包含默认值的集合
                       select new MenuNameDto
                       {
                           MenuId = a.MenuId,
                           MenuName = a.MenuName,
                           MenuUrl = a.MenuUrl,
                           ParentId = a.ParentId,
                           ParnetName = b.MenuName,
                           CreateBy = a.CreateBy,
                           CreateDate = a.CreateDate,
                           UpdateBy = a.UpdateBy,
                           UpdateDate = a.UpdateDate,
                           IsDeleted = a.IsDeleted,

                       };

            result.ToTaCount = linq.Count();
            result.ToTaPage = (int)Math.Ceiling(result.ToTaCount * 1.0 / request.Pagesizer);
            result.PageData = linq.OrderByDescending(x => x.MenuId).Skip((request.Pageidenx - 1) * request.Pagesizer).Take(request.Pagesizer).ToList();
            //result.Code = ApiEnum.Success;
            result.Message = "菜单列表显示成功";
            //result.Data = linq.ToList();
            return Task.FromResult(result);

        }




    }




}

